globals2 = globals()

from flask import *
import mss
import os
import subprocess as subp
import codecs
import threading
import flask_cors
import json

PATH = "monitor-1.png"


# addons

addnos = os.listdir("addnos")
for addon in addnos:
    path = os.path.join("addons", addon)
    with open(path+"/addons.json","r", encoding="utf-8") as mef:
        mef_content = mef.read()
    mef_content = json.loads(mef_content)
    namespace = mef_content["namespace"]
    orgin_main = mef_content["main"]
    version = mef_content["version"]
    name = mef_content["name"]
    info_author = mef_content["info"]["author"]
    info_email = mef_content["info"]["email"]
    info_description = mef_content["info"]["description"]
    addons_type = mef_content["type"]
    with open(path+"/"+namespace+"/"+orgin_main, "r", encoding="utf-8") as f:
        main_content = f.read()
    exec(main_content, globals2())



    
def mss_shot():
    with mss.mss() as sct:
        screenshot = sct.shot()
        sct.save(output='screenshot.png')

def check_path_type(path):
    try:
        open(path, "r").close()
        return "file"
    except IsADirectoryError:
        print(f"{path} is a directory")
        return "folder"
    except PermissionError:
        print(f"No permission to access {path}")
        return "np"
    except Exception as e:
        print(f"Error: {e}")
        return "unknown"

t = threading.Thread(target=mss_shot)



app = Flask(__name__)

flask_cors.CORS(app)

@app.route("/")
def index():
    return '114514'

"""
Read file
"""

@app.route("/GetFile/<path:filepath>")
def filepath(filepath):
    try:
        data = {
            "path":filepath,
            "content":str(open(filepath,"r",encoding="utf-8").read()).replace("\\n","<br>")
        }
        return jsonify(data)
    except FileNotFoundError as e:
        return "FileNotFoundError"
    
@app.route("/GetFileText/<path:filepath>")
def filepathnj(filepath):
    try:
        data = str(open(filepath,"r",encoding="utf-8").read()).replace("\n","<br>")
        return data
    except FileNotFoundError as e:
        return "FileNotFoundError"

@app.route("/RawFile/<path:filepath>")
def raw_file(filepath):
    try:
        return send_file(filepath)
    except FileNotFoundError as e:
        return jsonify({"error": "File not found"})

"""
ListDir
"""
@app.route("/ListDir/<path:filepath>")
def listdir(filepath):
    try:
        data={
            "dir":list(os.listdir(filepath))
        }
    except NotADirectoryError:
        return jsonify({"error": "Not a directory"})
    return jsonify(data)


"""
Updata file
"""
from flask import request, jsonify
import os

# UPLOAD_FOLDER = '/path/to/upload'  # 设置一个安全的上传目录
# os.makedirs(UPLOAD_FOLDER, exist_ok=True)

"""@app.route("/UpdataFile", methods=["POST"])
def updata_file():
    try:
        # 检查文件是否存在
        print(request.files)
        if 'file' not in request.files:
            return jsonify({"error": "未提供文件"}), 400
            
        file = request.files['file']
        if file.filename == '':
            return jsonify({"error": "无效文件名"}), 400
            
        # 安全处理文件名
        filename = file.filename
        save_path = os.path.join(UPLOAD_FOLDER, filename)
        
        # 保存文件
        print(type(file))
        
        return jsonify({
            "message": "文件上传成功",
            "filename": filename,
            "path": save_path
        })
        
    except Exception as e:
        print(e)
        return jsonify({"error": str(e)}), 500"""


"""
Run cmd.exe command
"""

@app.route("/RunCmd")
def runcmd():
    cmd_value = request.args.get('cmd')
    print(cmd_value)
    if not cmd_value:
        return jsonify({"error": "Please give cmd command"}), 400
    
    try:
        result = subp.run(
            cmd_value, 
            shell=True, 
            check=True,
            stdout=subp.PIPE, 
            stderr=subp.PIPE,
            universal_newlines=True
        )
        return jsonify({
            "cmd": cmd_value,
            "output": str(result.stdout).replace("\n","<br>"),
            "error": result.stderr,
            "returncode": result.returncode
        })
    except subp.CalledProcessError as e:
        return jsonify({
            "cmd": cmd_value,
            "output": str(e.stdout).replace("\n","<br>"),
            "error": e.stderr,
            "returncode": e.returncode,
            "message": "Command run is have error"
        }), 500
    except Exception as e:
        return jsonify({
            "cmd": cmd_value,
            "error": str(e),
            "message": "Have unkown error"
        }), 500
    

@app.route("/RunCmdText")
def run_cmd_text(): 
    cmd_value = request.args.get('cmd')
    if not cmd_value:
        return jsonify({"error": "Please give cmd command"}), 400
    
    try:
        result = subp.run(
            cmd_value, 
            shell=True, 
            check=True,
            stdout=subp.PIPE, 
            stderr=subp.PIPE,
            universal_newlines=True
        )
        
        return str(result.stdout).replace("\n", "<br>")

    except subp.CalledProcessError as e:
        return jsonify({
            "cmd": cmd_value,
            "output": str(e.stdout).replace("\n", "<br>"),
            "error": e.stderr,
            "returncode": e.returncode,
            "message": "Command run is have error"
        }), 500
    except Exception as e:
        return jsonify({
            "cmd": cmd_value,
            "error": str(e),
            "message": "Have unkown error"
        }), 500

# Screenshot

@app.route("/Desktop")
def desktop():
    mss_shot()
    return send_file(PATH)

# File operation

@app.route("/CheckPathType/<path:filepath>")
def CheckPathType(filepath):
    path_type = check_path_type(filepath)
    if path_type == "file":
        return jsonify({"type":"file"})
    elif path_type == "folder":
        return jsonify({"type":"folder"})
    elif path_type == "np":
        return jsonify({"type":"np"})
    else:
        return jsonify({"type":"unknown"})

if __name__ == "__main__":
    port =  5000
    app.run(port=port,debug=True,host="0.0.0.0")
